﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using ESSManageService.IServices;
using ESSManageService.Serilog;
using SqlSugar;
using SqlSugar.IOC;

namespace ESSManageService.Services
{
    public class SqlSugarRepository<T> : SimpleClient<T>, ISqlSugarRepository<T> where T : class, new()
    {
        /// <summary>
        /// 数据库客户端
        /// </summary>
        public ISqlSugarClient Db => base.Context;
        public SqlSugarRepository(ISqlSugarClient context = null) : base(context)
        {
            base.Context = DbScoped.SugarScope;
        }

        #region 分表操作

        public async Task<bool> SplitTableInsertAsync(T input)
        {
            return await base.AsInsertable(input).SplitTable().ExecuteCommandAsync() > 0;
        }

        public async Task<bool> SplitTableInsertAsync(List<T> input)
        {
            return await base.AsInsertable(input).SplitTable().ExecuteCommandAsync() > 0;
        }

        public async Task<bool> SplitTableUpdateAsync(T input)
        {
            return await base.AsUpdateable(input).SplitTable().ExecuteCommandAsync() > 0;
        }

        public async Task<bool> SplitTableUpdateAsync(List<T> input)
        {
            return await base.AsUpdateable(input).SplitTable().ExecuteCommandAsync() > 0;
        }

        public async Task<bool> SplitTableDeleteableAsync(T input)
        {
            return await base.Context.Deleteable(input).SplitTable().ExecuteCommandAsync() > 0;
        }

        public async Task<bool> SplitTableDeleteableAsync(List<T> input)
        {
            return await base.Context.Deleteable(input).SplitTable().ExecuteCommandAsync() > 0;
        }

        public Task<T> SplitTableGetFirstAsync(Expression<Func<T, bool>> whereExpression)
        {
            return base.AsQueryable().SplitTable().FirstAsync(whereExpression);
        }

        public Task<bool> SplitTableIsAnyAsync(Expression<Func<T, bool>> whereExpression)
        {
            return base.Context.Queryable<T>().Where(whereExpression).SplitTable().AnyAsync();
        }

        public Task<List<T>> SplitTableGetListAsync()
        {
            return Context.Queryable<T>().SplitTable().ToListAsync();
        }

        public Task<List<T>> SplitTableGetListAsync(Expression<Func<T, bool>> whereExpression)
        {
            return Context.Queryable<T>().Where(whereExpression).SplitTable().ToListAsync();
        }

        public Task<List<T>> SplitTableGetListAsync(Expression<Func<T, bool>> whereExpression, string[] tableNames)
        {
            return Context.Queryable<T>().Where(whereExpression).SplitTable(t => t.InTableNames(tableNames)).ToListAsync();
        }

        public bool TruncateTable()
        {
            return Context.DbMaintenance.TruncateTable<T>();
        }

        #endregion 分表操作
    }
}
